/**
 * 
 */
package com.thon.controller.system;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.codec.Base64;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.thon.commons.utils.ApplicationEnum.UserStatus;
import com.thon.controller.util.BaseController;
import com.thon.entity.user.User;
import com.thon.entity.user.UserBind;
import com.thon.service.user.UserBindService;
import com.thon.service.user.UserService;

/**
 * @author thon
 * @Date 2012-06-06 15:08
 */
@Controller
@RequestMapping("/login")
@SuppressWarnings({ "unchecked", "rawtypes" })
public class LoginController extends BaseController{
	@Autowired
	private UserService userService;
	@Autowired
	private UserBindService userBindService;
	
	private static final Log log = LogFactory.getLog(LoginController.class);
	@RequestMapping(method = RequestMethod.GET)
	public String login(Map<String, Object> map) {
		if (SecurityUtils.getSubject().isAuthenticated()) {
			return "index";
		}else {
			return "login";
		}
	}
	
	@RequestMapping(value = "/send/activating/mail",method = RequestMethod.POST)
	public ResponseEntity<HttpEntity> activatingMail(HttpServletRequest request){
		String loginName = request.getParameter("username");
		String plainPassword = request.getParameter("password");
		User user = userService.getUserByEmail(loginName);
		user.setPlainPassword(plainPassword);
		userService.registUser(user);
		return new ResponseEntity(HttpStatus.OK);
	}

	@RequestMapping(value = "/rest", method = RequestMethod.POST)
	public ResponseEntity<HttpEntity> login(HttpServletRequest request, Model model) {

		String username = request.getParameter("username");
		String password = request.getParameter("password");
		log.debug(username+":"+password);
		
		User user = userService.getUserByEmail(username);
		if(user==null)
			user = userService.getUserByName(username);
		if (user != null && user.getStatus().equals(UserStatus.open.getCode()) && user.getPassword().equalsIgnoreCase(userService.entryptPassword(password, user.getSalt()))) {
			String token = Base64.encodeToString((user.getLoginName()+":"+"").getBytes());
			model.addAttribute("token", token);
			model.addAttribute("user", user);
			return new ResponseEntity(model, HttpStatus.OK);
		}else if (user != null && user.getStatus().equals(UserStatus.locked.getCode())) {
			model.addAttribute("error", "locked");
			return new ResponseEntity(model, HttpStatus.LOCKED);
		}else {
			model.addAttribute("error", "user not found");
			return new ResponseEntity(model, HttpStatus.BAD_REQUEST);
		}
		
	}

	@RequestMapping(value = "/bind",method = RequestMethod.GET)
	public String binding(){
		
		return "login-bind";
	}
	
	@RequestMapping(value = "/bind", method = RequestMethod.POST)
	public ResponseEntity<HttpEntity> bindLogin(HttpServletRequest request, Model model) {
		UserBind oldUserBind = new UserBind();
		
		String bindToken = request.getParameter("token");
		//log.debug(">>>>>>>>>token:"+bindToken);
		oldUserBind = userBindService.getBindByToken(bindToken);
		//log.debug(">>>>>>>>>>>>old:"+oldUserBind);
		if (oldUserBind != null) {
			User user = new User();
			user = oldUserBind.getUser();
			String userToken = Base64.encodeToString((user.getLoginName()+":"+"").getBytes());
			model.addAttribute("token", userToken);
			model.addAttribute("user", user);
			return new ResponseEntity(model, HttpStatus.OK);
		}else {
			model.addAttribute("fail", "never binded");
			return new ResponseEntity(model,HttpStatus.ACCEPTED);
		}
	}
	@RequestMapping(method = RequestMethod.POST)
	public String fail(@RequestParam(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM) String userName, Model model) {
		model.addAttribute(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM, userName);
		return "login";
	}
}
